package org.example.java.util.colls;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * User: ZhangJuntao
 * Date: 13-12-20
 * Time: 下午5:18
 */
public class IterableTest {

  /**
   * 实现Iterable<E>接口的Person类
   */
  public static class Person implements Iterable<Person> {
    private String name;
    private int age;
    private List<Person> family;
    private List<Person> other;

    public Person() {
      super();
    }

    public Person(int size) {
      family = new ArrayList<Person>();
      other = new ArrayList<Person>();
      for (int i = 0; i < size; i++) {
        family.add(new Person("f" + i, i));
      }
      other.add(new Person("o" + 1, 1));
      other.add(new Person("o" + 2, 2));
    }

    public Person(String name, int age) {
      this.name = name;
      this.age = age;
    }

    /**
     * 实现Iterable接口中要求实现的方法
     */
    @Override
    public Iterator<Person> iterator() {
      return new PersonIterator();//返回一个MyIterator实例对象
    }

    public List<Person> getOther() {
      return other;
    }

    public void setOther(List<Person> other) {
      this.other = other;
    }

    /**
     * MyIterator是内部类，实现了Iterator<E>接口的类
     * 像这样的内部类，在网络上有很多这样的写法，我这里只是参考他们的写法罢了
     */
    private class PersonIterator implements Iterator<Person> {

      private int index = 0;

      @Override
      public boolean hasNext() {
        return index != family.size();
      }

      @Override
      public Person next() {
        return family.get(index++);
      }

      @Override
      public void remove() {
      }

    }

    public void add(Person person) {
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public int getAge() {
      return age;
    }

    public void setAge(int age) {
      this.age = age;
    }

    @Override
    public String toString() {
      return "person [name=" + name + ", age=" + age + "]";
    }

  }

  public static void main(String[] args) {
    //Iterator
    System.out.println("Iterator<Person>...");
    Person person = new Person(10);
    for (Person p : person) {
      System.out.println(p.toString());
    }
//    System.out.println("=======类似于下面=======");
//    Iterator<Person> iterator = person.iterator();
//    for (; iterator.hasNext(); ) {
//      System.out.println(iterator.next().toString());
//    }
    System.out.println("testPerson() method end\n");

  }

}
